from .node import Node
from .get_ancestor import get_ancestor


def make_active_node(root, basic_nodes=None):  # 将原本是休眠的节点状态改为激活
    if root.is_basic and (root.status == "Dormant" or root.status == "Warm"):
        root.status = 'Active'
        root.change_in_event = True
    elif not root.is_basic:
        for node in basic_nodes:
            ancestors = get_ancestor(node)
            stand = False
            for ancestor in ancestors:
                if ancestor.node_type == 'standby':
                    stand = True
                    ancestor_status = ancestor.update_status()
                    if ancestor_status == 'Failed':  # 按顺序开启子节点，直到这个祖先活过来
                        if node.status == "Dormant":
                            node.status = 'Active'
                            node.change_in_event = True
                    elif ancestor_status == 'Active':
                        for child in ancestor.children:
                            child_status = child.update_status()
                            if child_status == 'Active':
                                basic_nodes_tem = child.find_basic()
                                for node1 in basic_nodes:
                                    if node1.name in [node2.name for node2 in basic_nodes_tem]:
                                        make_active_node(node1)
                elif ancestor.node_type == 'warm_standby':
                    stand = True
                    ancestor_status = ancestor.update_status()
                    if node.status == "Dormant":
                        node.status = "Warm"
                        node.change_in_event = True
                    if ancestor_status == 'Failed':
                        if node.status == "Warm":
                            node.status = 'Active'
                            node.change_in_event = True
                    elif ancestor_status == 'Active':
                        for child in ancestor.children:
                            child_status = child.update_status()
                            if child_status == 'Active':
                                basic_nodes_tem = child.find_basic()
                                for node1 in basic_nodes:
                                    if node1.name in [node2.name for node2 in basic_nodes_tem]:
                                        make_active_node(node1)

            if stand is False and (node.status == "Dormant" or node.status == "Warm"):
                node.status = 'Active'
                node.change_in_event = True


def make_dormant_node(node):        # 将原本是failed的节点的状态改为休眠（维修完成后）
    node.status = "Dormant"
    for child in node.children:
        if child.status == "Failed":
            make_dormant_node(child)